package cn.stylefeng.roses.kernel.saas.sdk;

import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.db.api.pojo.druid.DruidProperties;
import cn.stylefeng.roses.kernel.dsctn.api.DataSourceApi;
import cn.stylefeng.roses.kernel.dsctn.api.context.CurrentDataSourceContext;
import cn.stylefeng.roses.kernel.dsctn.api.pojo.request.DatabaseInfoRequest;
import cn.stylefeng.roses.kernel.rule.constants.RuleConstants;
import cn.stylefeng.roses.kernel.saas.api.SaasTenantApi;
import cn.stylefeng.roses.kernel.saas.api.exception.SaasException;
import cn.stylefeng.roses.kernel.saas.api.exception.enums.SaasExceptionEnum;
import cn.stylefeng.roses.kernel.saas.sdk.factory.DataBaseInfoFactory;
import cn.stylefeng.roses.kernel.saas.sdk.util.SqlRunUtil;

/**
 * SaaS相关租户操作的sdk实现
 *
 * @author fengshuonan
 * @date 2021/2/18 17:15
 */
public class SaasTenantApiService implements SaasTenantApi {

    @Override
    public void changeTenant(String tenantCode) {
        CurrentDataSourceContext.setDataSourceName(RuleConstants.TENANT_DB_PREFIX + tenantCode);
    }

    @Override
    public void initTenantDb(String tenantCode, String tenantSqlResourceName) {

        // 1. 创建租户数据库
        DruidProperties druidProperties = SpringUtil.getBean(DruidProperties.class);
        String databaseName = RuleConstants.TENANT_DB_PREFIX + tenantCode;
        SqlRunUtil.createDatabase(druidProperties, databaseName);

        // 2. 创建租户的数据源记录
        DataSourceApi databaseInfoService = null;
        try {
            databaseInfoService = SpringUtil.getBean(DataSourceApi.class);
        } catch (Exception e) {
            throw new SaasException(SaasExceptionEnum.TENANT_DB_CREATE_ERROR, e.getMessage());
        }
        DatabaseInfoRequest dataBaseInfo = DataBaseInfoFactory.createDataBaseInfo(druidProperties, databaseName);
        databaseInfoService.add(dataBaseInfo);

        // 3. 初始化租户数据库
        String dbName = RuleConstants.TENANT_DB_PREFIX + tenantCode;
        SqlRunUtil.runClassPathSql(tenantSqlResourceName, dbName);
    }

}
